/*
 * @Author: liutongchao 1923236391@qq.com
 * @Date: 2023-04-26 15:26:41
 * @LastEditors: liutongchao 1923236391@qq.com
 * @LastEditTime: 2024-07-31 16:04:43
 * @FilePath: \greenbeeadmin\controllers\admin\login.go
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
package controllers

import (
	"fmt"
	adminService "greenbeeadmin/controllers/admin/service"
	greenbee "greenbeeadmin/controllers/greenbee"
	greenbeeUtils "greenbeeadmin/controllers/greenbee/utils"
	"greenbeeadmin/models"
	"net/url"
	"strconv"

	"github.com/beego/beego/v2/adapter/context"
	beego "github.com/beego/beego/v2/server/web"

	"github.com/beego/beego/v2/client/orm"
)

// 登陆 struct
type AdminLoginController struct {
	greenbee.AdminBaseController
}

// 退出登陆 struct
type AdminLogOutController struct {
	greenbee.AdminBaseController
}

// 找回密码 struct
type AdminForgetPassController struct {
	greenbee.AdminBaseController
}

/**
 * @description: 登录页
 * @return {*}
 */
func (c *AdminLoginController) Get() {
	var ctx *context.Context
	ctx = (*context.Context)(c.Ctx)
	//已登录
	if greenbee.IsLogin(ctx) {
		ctx.Redirect(302, "/admin")
	}
	c.TplName = "admin/login.html"
}

/**
 * @description: 登录提交
 * @return {*}
 */
func (c *AdminLoginController) Post() {
	user_name := c.GetString("username", "")
	password := c.GetString("password", "")
	verify_code := c.GetString("verifycode", "")
	verify_code_id := c.GetString("verifycode_id", "")
	var data interface{}
	msg := "登录失败"
	if !greenbee.CaptchaStore.Verify(verify_code_id, verify_code, true) {
		msg = "验证码错误"
		c.ErrorJson(500, msg, 0, data)
	}

	if user_name == "" {
		msg = "请输入账号"
		c.ErrorJson(500, msg, 0, data)
	}
	if password == "" {
		msg = "请输入密码"
		c.ErrorJson(500, msg, 0, data)
	}

	verify_pass := greenbeeUtils.Sha1(greenbeeUtils.Md5(password))
	//fmt.Println(verify_pass)
	o := orm.NewOrm()
	user_admin := models.AdminUser{UserName: user_name, Password: verify_pass, Is_del: 0}
	err := o.Read(&user_admin, "UserName", "Password", "Is_del")

	if err == orm.ErrNoRows {
		fmt.Println("查询不到")
		msg = "用户名密码错误"
	} else if err == orm.ErrMissPK {
		fmt.Println("找不到主键")
		msg = "找不到主键"
	} else {
		//是否被禁用
		if user_admin.Status == 1 {
			msg = "账号已被禁用"
			c.ErrorJson(500, msg, 0, data)
		}
		errs := c.SetSession("user", user_admin)
		if errs == nil {
			var adminUserService adminService.AdminUserService
			authorizationUrls := adminUserService.GetUserAuthorizationUrls(user_admin.Id)
			c.SetSession("userAuthorizationUrls", authorizationUrls)
			//设置登陆自动续期 1天
			admin_id_str := strconv.Itoa(user_admin.Id)
			system_key, _ := beego.AppConfig.String("greenbee_system_key")
			p := []byte(admin_id_str) //加密数据
			key := []byte(system_key) //加密key
			// AES CBC mode encryption
			ciphertext, _ := greenbeeUtils.Base64AESCBCEncrypt(p, key)
			cooikes := url.QueryEscape(ciphertext)
			c.Ctx.SetCookie("automatic_login", cooikes, 86400, "/")

			c.SuccessJson(200, data, 0)
		}
	}
	c.ErrorJson(500, msg, 0, data)
}

/**
 * @description:退出登录
 * @param
 * @return {*}
 */
func (c *AdminLogOutController) Get() {
	//删除session
	c.DelSession("user")
	c.DelSession("userAuthorizationUrls")
	//删除 登陆自动续期  cooike
	c.Ctx.SetCookie("automatic_login", "", 5, "/")
	// 跳转登录页,方式：301(永久移动),308(永久重定向),307(临时重定向)
	c.Redirect("/admin/login", 302)
}

/**
 * @description: 找回密码页
 * @return {*}
 */
func (c *AdminForgetPassController) Get() {
	var ctx *context.Context
	ctx = (*context.Context)(c.Ctx)
	//已登录
	if greenbee.IsLogin(ctx) {
		ctx.Redirect(302, "/admin")
	}
	c.TplName = "admin/forget_pass.html"
}

/**
 * @description: 发送验证码邮件
 * @return {*}
 */
func (c *AdminForgetPassController) Put() {
	user_name := c.GetString("username", "")
	verify_code := c.GetString("verifycode", "")
	verify_code_id := c.GetString("verifycode_id", "")
	var data string
	msg := "发送失败"
	if !greenbee.CaptchaStore.Verify(verify_code_id, verify_code, true) {
		msg = "图片验证码错误"
		c.ErrorJson(500, msg, 0, data)
	}

	if user_name == "" {
		msg = "请输入账号"
		c.ErrorJson(500, msg, 0, data)
	}

	o := orm.NewOrm()
	user_admin := models.AdminUser{UserName: user_name, Is_del: 0}
	err := o.Read(&user_admin, "UserName", "Is_del")

	if err == orm.ErrNoRows {
		fmt.Println("查询不到")
		msg = "账号有错误"
	} else if err == orm.ErrMissPK {
		fmt.Println("找不到主键")
		msg = "找不到主键"
	} else {
		//是否被禁用
		if user_admin.Status == 1 {
			msg = "账号已被禁用"
			c.ErrorJson(500, msg, 0, data)
		}
		//邮箱是否设置
		if user_admin.Email == "" {
			msg = "账号邮箱未设置，请联系管理员重置密码"
			c.ErrorJson(500, msg, 0, data)
		}

		//发送邮件
		verify_type := "email"
		name := user_admin.UserName
		var verificationService adminService.VerificationService
		verification_datas := verificationService.GetVerificationDatas(verify_type, name, 0)
		//每日最大发送量10条
		if len(verification_datas) > 10 {
			c.ErrorJson(500, "今天的邮件获取次数已用完，请明天再试", 0, data)
		}
		//查询邮箱配置信息
		email_data, err := c.GetSystemEmailSetingData()
		if err != nil {
			c.ErrorJson(500, err.Error(), 0, data)
		}
		if email_data.From_email == "" || email_data.From_passwd == "" || email_data.Server_host == "" || email_data.Server_port == "" {
			c.ErrorJson(500, "邮箱参数不全，请联系管理员配置邮箱参数", 0, data)
		}
		serverHost := email_data.Server_host
		fromEmail := email_data.From_email
		fromPasswd := email_data.From_passwd
		serverPort, _ := strconv.Atoi(email_data.Server_port)
		//生成验证数据
		rand_code, re := verificationService.CreateVerificationData(verify_type, name, 0)
		if !re {
			c.ErrorJson(500, "邮箱验证码创建失失败", 0, data)
		}
		to := []string{user_admin.Email}
		email_title := "密码重置验证邮件"
		email_content := "您正在进行重置密码操作，验证码是：" + rand_code + " 有效期10分钟。"
		res := greenbeeUtils.GomailSendToMail(to, email_title, email_content, serverHost, fromEmail, fromPasswd, serverPort)
		if res == "ok" {
			data = "验证码已发送到邮箱‘" + user_admin.Email + "’请注意查收"
			c.SuccessJson(200, data, 0)
		}
	}
	c.ErrorJson(500, msg, 0, data)
}

/**
 * @description: 重置密码
 * @return {*}
 */
func (c *AdminForgetPassController) Post() {
	user_name := c.GetString("username", "")
	new_password := c.GetString("new_password", "")
	email_captcha := c.GetString("email_captcha", "")

	var data interface{}
	msg := "密码修改失败"
	//邮箱验证码验证

	if user_name == "" {
		msg = "请输入账号"
		c.ErrorJson(500, msg, 0, data)
	}

	if len(new_password) < 6 {
		msg = "请输入大于6位长度新密码"
		c.ErrorJson(500, msg, 0, data)
	}

	//验证 邮箱验证码
	var verificationService adminService.VerificationService
	verify_type := "email"
	res := verificationService.ToVerificationData(verify_type, user_name, email_captcha)
	if !res {
		c.ErrorJson(500, "邮件验证码有误或已过期，请重新获取", 0, data)
	}

	//fmt.Println(verify_pass)
	o := orm.NewOrm()
	user_admin := models.AdminUser{UserName: user_name, Is_del: 0}
	err := o.Read(&user_admin, "UserName", "Is_del")

	if err == orm.ErrNoRows {
		fmt.Println("查询不到")
		msg = "用户名不存在"
	} else if err == orm.ErrMissPK {
		fmt.Println("找不到主键")
		msg = "找不到主键"
	} else {
		//是否被禁用
		if user_admin.Status == 1 {
			msg = "账号已被禁用"
			c.ErrorJson(500, msg, 0, data)
		}
		// 更改密码
		var adminUserService adminService.AdminUserService
		var user models.AdminUser
		user.Password = greenbeeUtils.Sha1(greenbeeUtils.Md5(new_password))
		updateField := []string{"Password"}

		//编辑用户
		re := adminUserService.UserEdit(user, user_admin.Id, updateField)
		if re > 0 {
			c.SuccessJson(200, data, 0)
		}
	}
	c.ErrorJson(500, msg, 0, data)
}
